<!--
  智慧小区管理系统 - 面包屑导航组件
  @author Wu.Liang
  @date 2024-01-01
-->
<template>
  <div class="breadcrumb-container">
    <el-breadcrumb :separator-icon="ArrowRight" class="app-breadcrumb">
      <transition-group name="breadcrumb">
        <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
          <span v-if="item.redirect === 'noRedirect' || index === breadcrumbList.length - 1" class="no-redirect">
            {{ item.meta?.title }}
          </span>
          <a v-else @click.prevent="handleLink(item)">
            {{ item.meta?.title }}
          </a>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowRight } from '@element-plus/icons-vue'

// 路由
const route = useRoute()
const router = useRouter()

// 面包屑列表
const breadcrumbList = ref<any[]>([])

// 获取面包屑列表
const getBreadcrumb = () => {
    // 过滤掉没有meta.title的路由
    let matched = route.matched.filter(item => item.meta && item.meta.title)

    // 如果第一个不是首页，则添加首页
    const first = matched[0]
    if (!isDashboard(first)) {
        matched = [{ path: '/dashboard', meta: { title: '首页' } }].concat(matched)
    }

    breadcrumbList.value = matched.filter((item) => {
        return item.meta && item.meta.title && item.meta.breadcrumb !== false
    })
}

// 判断是否是首页
const isDashboard = (route: any) => {
    const name = route && route.name
    if (!name) {
        return false
    }
    return name.toString().trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
}

// 处理链接点击
const handleLink = (item: any) => {
    const { redirect, path } = item
    if (redirect) {
        router.push(redirect)
        return
    }
    router.push(path)
}

// 监听路由变化
watch(route, getBreadcrumb, { immediate: true })
</script>

<style scoped lang="scss">
.breadcrumb-container {
  padding: 0 16px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;

  .app-breadcrumb {
    display: inline-block;
    font-size: 14px;
    line-height: 50px;

    .no-redirect {
      color: #97a8be;
      cursor: text;
    }

    a {
      color: #2d8cf0;
      text-decoration: none;
      transition: color 0.2s ease;

      &:hover {
        color: #1c6dd0;
      }
    }
  }
}

// 面包屑动画
.breadcrumb-enter-active,
.breadcrumb-leave-active {
  transition: all 0.3s ease;
}

.breadcrumb-enter-from,
.breadcrumb-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.breadcrumb-leave-active {
  position: absolute;
}

@media (max-width: 768px) {
  .breadcrumb-container {
    padding: 0 12px;

    .app-breadcrumb {
      font-size: 12px;
      line-height: 40px;
    }
  }
}
</style>
